#include "dynamicchartview.h"
#include <QtCharts>
#include <QDebug>

QT_CHARTS_USE_NAMESPACE

DynamicChartView::DynamicChartView(QWidget *parent) :
        QChartView(parent),
        chart(new QChart), series(new QLineSeries),
        axisX(new QValueAxis),
        // axisX(new QDateTimeAxis),
        axisY(new QValueAxis),
        // baseDate(QDate::currentDate()),
        scrollStep(5), curPointX(0), curPointY(0) {
    // 配置chart, 要先加series
    chart->addSeries(series.get());
    chart->addAxis(axisX.get(), Qt::AlignBottom);
    chart->addAxis(axisY.get(), Qt::AlignLeft);
    // 隐藏图例
    chart->legend()->hide();

    // 配置坐标轴
    // axisX->setRange(QDate().startOfDay(), QDateTime());
    axisX->setRange(0, 50);
    // x轴间距
    axisX->setTickCount(10);
    // axisX->setFormat("mm:ss");
    // axisX->hide();
    // axisX->setLabelsVisible(false);
    axisX->setLabelsAngle(30);
    // gapValWidth = (axisX->max() - axisX->min()) / axisX->tickCount();

    axisY->setRange(0, 10);
    axisY->setTickCount(3);

    // 配置series
    series->attachAxis(axisX.get());
    series->attachAxis(axisY.get());
    series->setPointsVisible();

    setChart(chart.get());

    seriesTimer.setInterval(300);
    connect(&seriesTimer, &QTimer::timeout, this, &DynamicChartView::handleTimeout);
}

void DynamicChartView::handleTimeout() {
    // 间距像素宽度,像素可能会变
    addPoint(ReactionModel::next());
    // 移动一个间隔的像素宽度
    if (curPointX > axisX->max()) {
        axisX->setRange(curPointX - 50, curPointX);
    }

}

void DynamicChartView::startTimer() {
    if (seriesTimer.isActive()) return;
    seriesTimer.start();
}

void DynamicChartView::stopTimer() {
    if (!seriesTimer.isActive()) return;
    seriesTimer.stop();
}

void DynamicChartView::addPoint(qreal y) {
    series->append(curPointX, y);
    curPointX ++;
}



